package com.baichuan.util;

import lombok.extern.slf4j.Slf4j;

/**
 * cms用户token工具
 *
 * @author leo
 * @version 1.0
 * @date 2020年4月3日
 */
@Slf4j
public class CmsUserTokenUtil {
    //token有期时长1天
    public static long TOKEN_VALIDITY = 1000l * 60 * 60 * 24;

    private static String SPACE = "_#_";

    /**
     * 验证token合法性，token组成：时间戳 + "_#_" + 用户id + "_#_" + 时间戳
     *
     * @param token
     * @return
     */
    public static boolean isVerifyToken(String token) {
        if (StringUtils.isEmpty(token))
            return false;
        try {
            String decryptedStr = SimpleEncrypt.decrypt(token);
            String[] arr = decryptedStr.split(SPACE);
            if (arr.length != 3)
                return false;
            // //时间戳timestamp
            String timestamp1 = arr[0];
            // userId
            String userId = arr[1];
            //时间戳timestamp
            String timestamp2 = arr[2];
            if (!timestamp1.equals(timestamp2))
                return false;
            if (System.currentTimeMillis() - Long.parseLong(timestamp1) > TOKEN_VALIDITY)
                return false;
            return true;
        } catch (Exception e) {
            log.error("token:{}解密token失败，错误信息为{}", token, e.getMessage());
            return false;
        }
    }

    public static String getToken(Integer userId) {
        long currentTimeMillis = System.currentTimeMillis();
        String encryptStr = currentTimeMillis + SPACE + userId + SPACE + currentTimeMillis;
        return SimpleEncrypt.encrypt(encryptStr);
    }

    public static Integer getUserId(String token) {
        if (token == null || "".equals(token))
            return null;
        try {
            String str = SimpleEncrypt.decrypt(token);
            String[] arr = str.split(SPACE);
            return Integer.parseInt(arr[1]);
        } catch (Exception e) {
            log.error("getUserId token:{}", token, e);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(CmsUserTokenUtil.getToken(1));
    }
}
